<?php

namespace app\uapi\controller;

use app\admin\model\KnscyComment;
use app\admin\model\KnscyMessage;
use app\admin\model\KnscyOrderLogs;
use app\admin\model\KnscyOrders;
use app\admin\model\KnscyUsers;
use app\common\controller\ApiController;
use app\common\service\UploadService;
use app\common\service\WeginService;
use think\facade\Db;

/**
 * 用于管理用户中心的功能
 */
class Center extends  ApiController
{

    public static $needLoginAction = [
        'paymentLogs',
        'upload', //上传图片
        'myComments', //用户的评论
        'getEditComment', //用户编辑发布的评论
        'postComment', //用户发布
        'deleteComment',//删除评论
    ];
    public function upload()
    {
        $this->checkPostRequest();
        $data = [
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'file|指定上传类型有误'  => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = UploadService::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {

            $this->success($upload['msg'], [
                'url' => get_full_url($upload['url']),
                'save_url'=>$upload['url']
            ]);
        } else {
            $this->error($upload['msg']);
        }
    }
    /**
     * 用户支付记录，只有订单在线付款的记录
     * @return void
     */
    public function paymentLogs()
    {
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        // $type = $this->request->post('type', 0);
        $list = KnscyOrders::where('user_id', $this->user_id)
                //withoutGlobalScope(['uniacid'])-> alias('o')
                //->where('o.uniacid', WeginService::getUniacid())
                ->where('pay_money','>',0)
                ->where('pay_status', 3)
                //->where('l.tag','pay.notify.process')
                //->join(KnscyOrderLogs::getTable()." l","l.order_id=o.id")
                ->paginate(
                    [
                        'list_rows' => $limit,
                        'page' => $page,
                    ]
                );
        $this->success('success', $list);
    }

    /**
     * 用户发布的评论
     * @return void
     */
    public function myComments(){
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        $myCount = KnscyComment::where('user_id', $this->user_id)->count();
        $list = KnscyComment::where( 'user_id',$this->user_id)
            ->order(Db::raw('sort=0,sort asc,id desc'))
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function($item){
                $arr = explode("|",$item['thumbs']);
                foreach($arr as $key=> $log){
                    $arr[$key] = get_full_url($log);
                }
                $item['thumbs'] =  $arr;
                $item['avatar'] = get_full_url($item['avatar']);
                $item['date_label'] = date('Y-m-d',strtotime($item['create_time']));
            });
        //查询是否有订单记录
        $canSend = KnscyOrders::where('user_id', $this->user_id)->count();
        $this->success('success',
            [
                'list'=> $list,
                'canSend'=>$canSend,
                'myCount'=>$myCount
            ]
        );
    }
    /**
     * 用户删除自己的评论
     */
    public function deleteComment(){
        $id = $this->request->post('id');

        $info = KnscyComment::where('id', $id)->where('user_id', $this->user_id)->find();
        if($info){
           $info->delete();
           $this->success('success');
        }
        $this->error('参数有误');
    }
    /**
     * 用户发布保存评论
     * @return void
     */
    public function postComment()
    {
        $post = $this->request->post();
        $rule = [
            'nickname|昵称' => 'require|min:2|max:20',
            'content|评论内容' => 'require|min:30',
            'thumbs|图片' => 'require',
        ];
        $this->validate($post, $rule);
        $post['user_id'] = $this->user_id;
        $post['status'] = 0;// 进入审核阶段
        if(empty($this->userInfo['head_img']))
            $post['avatar']  = "/addons/kbwdl_nickscenery/public/images/get_avatar.png";
        else
            $post['avatar']  = $this->userInfo['head_img'];

        if($post['id']>0){
            $model = KnscyComment::where('id', $post['id'])->find();
        }else{
            $model = new KnscyComment();
        }

        $save = $model->save($post);
        $this->success('success', $save);
    }

    /**
     * 获取某条评论用于编辑
     * @return void
     */
    public function getEditComment()
    {
        $id = $this->request->post('id', 0);
        $info = KnscyComment::where('id', $id)->where('user_id', $this->user_id)->find();
        //处理图片用于编辑
        $arr = explode("|",$info['thumbs']);
        $thumbs = [];
        foreach($arr as $key=> $log){
            $thumbs[$key]['url'] = get_full_url($log);
            $thumbs[$key]['save_url'] = $log;
        }
        $info['thumbs'] =  $thumbs;
        $this->success('success',$info);
    }
    /**
     * 评论数据
     */
    public function recentComment(){
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        $list = KnscyComment::where('status', 1)
                ->order(Db::raw('sort=0,sort asc,id desc'))
                ->paginate(
                    [
                        'list_rows' => $limit,
                        'page' => $page,
                    ]
                )->each(function($item){
                $arr = explode("|",$item['thumbs']);
                foreach($arr as $key=> $log){
                    $arr[$key] = get_full_url($log);
                }
                $item['thumbs'] =  $arr;
                $item['avatar'] = get_full_url($item['avatar']);
                $item['date_label'] = date('Y-m-d',strtotime($item['create_time']));
            });
        $this->success('success', $list);
    }


    /**
     * 我的站内消息列表
     * @return
     */
    public function myMessageList()
    {
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);

        $list = KnscyMessage::where('user_id', $this->user_id)
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function($item){
                $item['create_time_label'] = date('Y-m-d H:i', strtotime($item['create_time']));
            });
        $this->success('success', $list);
    }

}